package com.tfswue.springboot_demo02.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
//开启websecurity配置
@EnableWebSecurity
public class SecurityConfig {
    //配置密码加密器（必需）
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();// 使用BCrypt 强哈希加密

    }
    //配置用户存储（内存方式，生产环境需要链接数据库）
    @Bean
    public UserDetailsService userDetailsService(){
        //创建两个测试用户
        UserDetails user = User.builder()
                .username("user")
                .password(passwordEncoder().encode("pass"))//密码必须加密
                .roles("USER")//分配角色
                .build();

        UserDetails admin = User.builder()
                .username("admin")
                .password(passwordEncoder().encode("admin"))//密码必须加密
                .roles("ADMIN", "USER")//分配角色
                .build();
        return new InMemoryUserDetailsManager(user, admin);//存储在内存中
    }
    //核心安全配置（HTTP 请求过滤规则）
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{
        http
                .authorizeHttpRequests((authorize) -> authorize
                        .requestMatchers("/", "/index").permitAll()//允许根路径匿名访问
                        .requestMatchers("/public/**").permitAll()//公共路径无需认证
                        .requestMatchers("/admin/**").hasRole("ADMIN")//仅管理员访问
                        .requestMatchers("/api/**").hasAnyRole("USER")
                        .anyRequest().authenticated())//其他请求需要认证
                .formLogin((form) -> form
                        .loginPage("/index.html")//与实际文件路径一致
                        .loginProcessingUrl("/login")//处理登录的URL
                        .defaultSuccessUrl("/public/hello")//登录成功共固定跳转到此路径
                        .permitAll())
                .logout((logout) -> logout
                        .logoutSuccessUrl("/public/goodbye")
                        .permitAll())
                .csrf(csrf -> csrf.disable());//禁用CSRF保护（开发环境方便测试）
        return http.build();

    }
}
